from vj import *
from OpenGL.GL import *
from math import *
import random
from polygon import *
from shader import *

def sign(x): return (x>0)-(x<0)

def turnsignal(a,b,c):
    return -(c[0]-b[0])*(b[1]-a[1])+(c[1]-b[1])*(b[0]-a[0])

def convhull(lst):
    pts=lst[:]
    pts.sort(lambda v,w: sign(v[1]-w[1]))
    pivot=pts[0]
    pts.remove(pivot)
    pts.sort(lambda v,w: sign(math.atan2(v[1]-pivot[1],v[0]-pivot[0])-
                            math.atan2(w[1]-pivot[1],w[0]-pivot[0])))
    res=[pivot, pts[0]]
    for x in pts[1:]:
        while turnsignal(res[-2],res[-1],x)<0:
            res.remove(res[-1])
        res.append(x)
    return res

class Simplex:

	def __init__(self):
	
		self.num = random.randint(10,30)
		self.generate()
		
		self.shader = MyMaterial("sphere.glsl")
		self.sh = False
	
	def generate(self):

		self.sim = [vector([random.random(),random.random(),random.random() ])for a in range(self.num)]
		self.hull = convhull(self.sim)
		
	def update(self,rtri):
	
		if self.sh:
		
			self.shader.activate()
			
	#		self.loc1 = glGetUniformLocationARB(self.shader.m_program,"n")
	#		glUniform1fARB(self.loc1,3.0)

			self.loc1 = glGetUniformLocationARB(self.shader.m_program,"LightPosition")
			self.loc2 = glGetUniformLocationARB(self.shader.m_program,"SurfaceColor")			glUniform3fARB(self.loc1,1.0,1.0,1.0)			glUniform3fARB(self.loc2,1.0,1.0,1.0)	

			self.loc1 = glGetUniformLocationARB(self.shader.m_program,"Radius")
			self.loc2 = glGetUniformLocationARB(self.shader.m_program,"Blend")			glUniform1fARB(self.loc1,sin(0.1*rtri+1.0))			glUniform1fARB(self.loc2,cos(rtri))	
			
			self.shader.deactivate()
		
	def draw(self):
	
		glColor4f(1,1,1,1)
		if self.sh:
			self.shader.activate()
			
		glLineWidth(2.0)
		glBegin(GL_LINES)
		
		for v in self.sim:
			for c in self.hull:
			
				glVertex3f(v[0],v[1],v[2])
				glVertex3f(c[0],c[1],c[2])
				
		glEnd()
		
		if self.sh:
			self.shader.deactivate()